package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 假设ImageGenerator工具类在以下包中，请根据实际情况调整
import cn.edu.pzhu.javaweb.util.ImageGenerator;

/**
 * Servlet implementation class CreateCaptchaServlet
 */
@WebServlet("/captcha")
public class CreateCaptchaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateCaptchaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 设置响应类型为图像image/jpeg
		response.setContentType("image/jpeg");
		
		// 2. 初始化工具类的实例util
		ImageGenerator util = new ImageGenerator();
		
		// 初始化图像：宽120px，高40px，4个字符（可根据需要调整）
		util.initialize(120, 40, 4);
		
		// 3. 调用util获得生成的图像
		// 4. 调用util获得生成图像的验证码
		String captchaText = util.getText();
		
		// 6. 将验证码保存到session
		HttpSession session = request.getSession();
		session.setAttribute("captcha", captchaText);
		
		// 可选：设置session超时时间（5分钟）
		session.setMaxInactiveInterval(5 * 60);
		
		// 5. 将图像输出到前端
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			// 获取图像的JPEG格式字节数组并输出
			byte[] imageBytes = util.getImageBytes("JPEG");
			outputStream.write(imageBytes);
			outputStream.flush();
		} catch (Exception e) {
			// 记录错误日志
			System.err.println("生成验证码图像时发生错误: " + e.getMessage());
			e.printStackTrace();
		} finally {
			// 确保输出流被关闭
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}